package com.ruoyi.web.controller.payment.ceshi1;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.zhuangxiumain.vo.ZhiFuVo;
import org.jdom2.JDOMException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by 小董 on 2021/2/2 20:57
 */
@RestController
@RequestMapping("/api/wxPay")
public class Controller extends BaseController {


    @PostMapping("/weiXinZhi")
    public AjaxResult zhiFu(@RequestBody ZhiFuVo zhiFuVo){
        try {
            Map<String,Map<Object,Object>> resultMap = new HashMap<>();
            //测试环境
            //微信默认从单位为分，所以用此方法将单位调整成元
            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid", ConfigUtil.APPID);
            parameters.put("mch_id", ConfigUtil.MCH_ID);
            parameters.put("nonce_str", qian.CreateNoncestr());
            parameters.put("body", "测试测试");
            parameters.put("out_trade_no", UUID.randomUUID().toString().substring(0, 15)); //订单id
            parameters.put("fee_type", "CNY");
            parameters.put("total_fee", "10");
            parameters.put("spbill_create_ip", "127.0.0.1");
            parameters.put("notify_url", "http://www.weixin.qq.com/wxpay/pay.php");
            parameters.put("trade_type", "APP");
            //设置签名
            String sign = qian.createSign("UTF-8", parameters);
            parameters.put("sign", sign);
            //封装请求参数结束
            String requestXML = qian.getRequestXml(parameters);
            //调用统一下单接口
            String result = qian.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
            System.out.println("\n" + result);
                /**统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appId，partnerId，prepayId，nonceStr，timeStamp，package。注意：package的值格式为Sign=WXPay**/
                Map<String, String> map = XMLUtil.doXMLParse(result);
                SortedMap<Object, Object> parameterMap2 = new TreeMap<Object, Object>();
                parameterMap2.put("appid", ConfigUtil.APPID);
                parameterMap2.put("partnerid", ConfigUtil.MCH_ID);
                parameterMap2.put("prepayid", map.get("prepay_id"));
                parameterMap2.put("package", "Sign=WXPay");
                parameterMap2.put("noncestr", qian.CreateNoncestr());
                //本来生成的时间戳是13位，但是ios必须是10位，所以截取了一下
                parameterMap2.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
                String sign2 = qian.createSign("UTF-8", parameterMap2);
                parameterMap2.put("sign", sign2);//此 parameterMap2内容送到ios调用就可以了
               /* landlordNew.setWxSign(sign2);
                this.landlordNewService.update(landlordNew);*/
                resultMap.put("msg", parameterMap2);
                return AjaxResult.success(resultMap);
        }catch (JDOMException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error();
    }


    /**
     * 微信异步通知 （签约支付）
     */
    @RequestMapping("/wxNotifySignContract")
    public void wxNotifySignContract(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        try {
            //读取参数
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            //解析xml成map
            Map<String, String> m = new HashMap<String, String>();
            m = XMLUtil.doXMLParse(sb.toString());
            for (Object keyValue : m.keySet()) {
                System.out.println(keyValue + "=" + m.get(keyValue));
            }
            //过滤空 设置 TreeMap
            SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
            Iterator it = m.keySet().iterator();
            while (it.hasNext()) {
                String parameter = (String) it.next();
                String parameterValue = m.get(parameter);

                String v = "";
                if (null != parameterValue) {
                    v = parameterValue.trim();
                }
                packageParams.put(parameter, v);
            }

            //判断签名是否正确
            String resXml = "";
            if (qian.isTenpaySign("UTF-8", packageParams)) {
                if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                    // 这里是支付成功
                    //////////执行自己的业务逻辑////////////////
                    String appid = (String) packageParams.get("appid");//appid
                    String sign = (String) packageParams.get("sign");//签名
                    String total_fee = (String) packageParams.get("total_fee");//总金额
                    String mch_id = (String) packageParams.get("mch_id"); //商户号
                    String openid = (String) packageParams.get("openid");  //用户标识

                    //微信回调 商户号回调的商户订单号是out_trade_no
                    //（需要唯一，同一个订单号执行下单接口会报错），这里笔者使用
                    //nonce_str作为订单号，后续还需要改动。这个字段官方文档解释为随机字
                    //符串，但后来发现回调的时候返回的nonce_str跟下单填进去的nonce_str
                    //一致，所以暂时用来当订单号了。）
                    String out_trade_no = (String) packageParams.get("nonce_str"); //商户订单号
                    String transaction_id = (String) packageParams.get("transaction_id"); //微信支付订单号
//                    this.contractpayReturn(appid, sign, total_fee, mch_id, openid, out_trade_no, transaction_id);
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                } else {
                    logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
                    resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                }
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
                logger.info("通知签名验证失败");
            }
            //------------------------------
            //处理业务完毕
            //------------------------------
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
            logger.error("微信回调接口成功--------");
        } catch (Exception ex) {
            logger.error(ex.toString());
            logger.error("微信回调接口失败--------");
        }
    }

}
